package demo;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Table;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Table(schema = "Demo")
public class MemberServiceImpl implements MemberService {
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    private Session getSession() {
        return SessionFactoryUtils.getSession(sessionFactory, true);
    }
    
    public Member findMember(int memberId) {
        return get(Member.class, memberId);
    }
    
    @Transactional
    public void deleteMember(Member member) {
        getSession().delete(member);
    }
    
    @Transactional
    public void saveOrUpdate(Member member, String note) {
        getSession().saveOrUpdate(member);
        MemberNote memberNote = new MemberNote();
        memberNote.setMember(member);
        memberNote.setNote(note);
        getSession().save(memberNote);
        
    }
    
    @Transactional(readOnly=true)
    public List<MemberNote> findNotesByMember(Member member) {
        return getSession().createQuery("from MemberNote mn where mn.member = :member").setEntity("member", member).list();
    }
    
    
    public MemberNote findMemberNote(int memberNoteId) {
        return get(MemberNote.class, memberNoteId);
    }
    
    private <T> T get(Class<T> clazz, int id) {
        return (T) getSession().get(clazz, id);
    }
    
}
